package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.UpdateArticleMess;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    CacheService cacheService;
    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null ||
                dto.getOperation() > 1 || dto.getOperation() < 0 || dto.getType() > 2 || dto.getType() < 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取登录人信息
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存点赞/取消点赞数据
        if (dto.getOperation() == 0) {
            //判断已点赞不能重复点
            Double score = cacheService.zScore(UserRelationConstants.LIKE_LIST + apUser.getId(), dto.getArticleId().toString());
            if (score != null) {
                CustException.cust("请不要重复点赞");
            }
            //点赞
            cacheService.zAdd(UserRelationConstants.LIKE_LIST + apUser.getId(), dto.getArticleId().toString(), System.currentTimeMillis());

            //*****kafka发送消息,实时计算热点分数******
            UpdateArticleMess mess = new UpdateArticleMess();
            mess.setArticleId(dto.getArticleId());
            mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
            kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSON.toJSONString(mess));
            //****************


        } else {
            //取消点赞
            cacheService.zRemove(UserRelationConstants.LIKE_LIST + apUser.getId(), dto.getArticleId().toString());
        }
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
